<template>
  <div>
    <canvas ref="qrcodeCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import QRCode from 'qrcode'

const props = defineProps({
  qrUrlStr: {
    type: String,
    required: true
  }
})

const qrcodeCanvas = ref(null)

const generateQRCode = async () => {
  if (!qrcodeCanvas.value) return
  
  const opts = {
    errorCorrectionLevel: 'H',
    type: 'image/png',
    quality: 0.3,
    margin: 0,
    width: 120,
    height: 120,
    color: {
      dark: '#333333',
      light: '#fff'
    }
  }

  try {
    await QRCode.toCanvas(qrcodeCanvas.value, props.qrUrlStr, opts)
  } catch (error) {
    console.error('生成二维码失败:', error)
  }
}

watch(() => props.qrUrlStr, (newValue) => {
  if (newValue) {
    generateQRCode()
  }
}, { immediate: true })

onMounted(() => {
  generateQRCode()
})
</script>

<style scoped>
/* 独立组件的样式，写这里，支持标准的css语法 */
</style>